/**
 * @author LYJ
 * Created by Administrator on 2018/2/27 0027.
 */
function FoodsTable($Table,type) {
    var This = this;
    this.div = $Table;
    this.type = type;
    this.tableBar = null;
    this.toolBar = null;
    this.myToolBar = null;
    this.errorBar = null;
    this.path = "../static/";

    this.foodsForm = null;

    $(function () {
        This.div.html("");
        This.createTool.init();//表工具
        This.createTable.init();//创建数据表
    });

    this.createTool  = {
        init: function () {
            this.bar();
            this.element();
            this.event();
        },
        bar: function () {
            var toolbar =
                '<div class="error"></div>'+
                '<div class="myToolbar"><div class="fClear" style=" clear:both;"></div></div>'+
                '<div class="toolbar btn-group pull-right"  style="margin-right: 10px" ></div>';
            This.div.append(toolbar);
            This.errorBar = This.div.find(".error");
            This.errorBar.hintModal();
            This.toolBar = This.div.find(".toolbar");
            This.myToolBar = This.div.find(".myToolbar");
        },
        element: function () {
            addTool(
                '<button class="add btn btn-default ">' +
                    '<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增' +
                '</button>'+
                '<button class="update btn btn-default">' +
                    '<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span><span>修改</span>' +
                '</button>'+
                '<button class="upOfStock btn btn-default FL">' +
                    '<span class="glyphicon glyphicon-arrow-up" aria-hidden="true"></span>上架' +
                '</button>'+
                '<button class="outOfStock btn btn-default FL">' +
                '<span class="glyphicon glyphicon-arrow-down" aria-hidden="true"></span>下架' +
                '</button>'
            );
            addMyTool(
                '<select class="select btn btn-default FL " style="margin-right: 10px"></select>' +
                '<div class="where input-group FL " style="width: 200px">' +
                    '<input type="text" class="form-control" placeholder="商品名"/>' +
                    '<span class="input-group-btn">' +
                        '<button class="btn btn-default">搜索</button>' +
                    '</span>' +
                '</div>'
            );
        },
        event: function () {
            getTool("add").bind("click",function () {
                This.foodsForm.$modal.hintModal().showDiv();
                This.foodsForm.setType("add");
            });
            getTool("update").bind("click",function () {
                var rows = This.tableBar.bootstrapTable("getSelections");
                if(!rows || rows == ""){
                    return null;
                }else{
                    This.ajaxTable.update(rows[0]);
                }
            });
            getTool("upOfStock").bind("click",function () {
                var ids = [];
                $.each(This.tableBar.bootstrapTable("getSelections"),function(i,rows){
                    ids.push(rows["fid"]);
                });
                This.ajaxTable.stock(ids,"up");
            });
            getTool("outOfStock").bind("click",function () {
                var ids = [];
                $.each(This.tableBar.bootstrapTable("getSelections"),function(i,rows){
                    ids.push(rows["fid"]);
                });
                This.ajaxTable.stock(ids,"out");
            });
            
            var select = getMyTool("select");
            var where = getMyTool("where");
            select.on("change",function () {
                This.tableBar.bootstrapTable("refresh");
            });
            Select.injectData(getMyTool("select"),foodTypeSelect, "typeid", "typename","全部商品", 0);
            where.find("button").bind("click",function () {
                This.tableBar.bootstrapTable("refresh");
            });
        }


    };

    this.createTable = {
        init: function () {
            var tableHtml = '<table style="min-width: 700px"></table>';
            This.div.append(tableHtml);
            This.tableBar = This.div.find("table");

            var table = This.tableBar;
            table.bootstrapTable({
                method: 'post',                      //请求方式（*）
                url: "foods/get",         //请求后台的URL（*）
                queryParams: function (params) {
                    return {
                        offset:params.offset,
                        limit: params.limit,
                        foodTypeId:getMyTool("select").val(),
                        where:getMyTool("where").find("input").val()
                    };
                },
                toolbar: '.toolbar',                //工具按钮用哪个容器
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                sortable: false,                     //是否启用排序
                sortOrder: "asc",                   //排序方式

                pagination: true,                   //是否显示分页（*）
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,                       //初始化加载第一页，默认第一页
                pageSize: 25,                       //每页的记录行数（*）
                pageList: [25, 50, 100],        //可供选择的每页的行数（*）
                contentType: "application/x-www-form-urlencoded",
                // height:$(document).height() - This.div.offset().top - 20,
                showColumns: true,                  //是否显示所有的列
                showRefresh: true,                  //是否显示刷新按钮
                minimumCountColumns: 2,             //最少允许的列数
                clickToSelect: true,                //是否启用点击选中行
                uniqueId: "id",                     //每一行的唯一标识，一般为主键列
                detailView: false,                   //是否显示父子表
                columns: [
                    {
                        field: 'checkStatus',
                        checkbox: true,
                        valign:"middle"
                    },
                    {
                        width: "5%",
                        align: "center",
                        formatter: function (value, row, index) {
                            var options = table.bootstrapTable('getOptions');
                            return options.pageSize * (options.pageNumber - 1) + index + 1;
                        }
                    },
                    {
                        field: 'picurl',
                        align: "center",
                        valign: "middle",
                        formatter: function (value, row, index) {
                            return "<img src='"+This.path+value+"' width='30px' height='30px'>";
                        }
                    },
                    {
                        title:'名称',
                        field: 'foodname',
                        align: "center",
                        valign: "middle"
                    },
                    {
                        title:'分类',
                        field: 'type.typename',
                        align: "center",
                        valign: "middle"
                    },
                    {
                        title:'价格',
                        field: 'foodprice',
                        align: "center",
                        valign: "middle"
                    },
                    {
                        title:'vip价格',
                        field: 'foodvip',
                        align: "center",
                        valign: "middle"
                    },
                    {
                        title: '特色',
                        field: 'feature',
                        align: "center",
                        valign: "middle"
                    },
                    {
                        title: '状态',
                        field: 'state',
                        align: "center",
                        valign: "middle",
                        formatter:function (value, row, index) {
                            if(value == 0){
                                return '<div class="img_container"><div class="state_div"><div class="state_label_small label_error">下架</div></div></div>'
                            }else{
                                return null;
                            }
                        }
                    },
                    {
                        title: '创建时间',
                        field: 'createTime',
                        align: "center",
                        valign: "middle",
                        formatter:function (value, row, index) {
                            if(value != null){
                                return '<p  data-toggle="tooltip" title="'+value+'">'+value.split(" ")[0]+'</p>';
                            }
                        }
                    },
                    {
                        field: 'operate',
                        title: '操作',
                        align: "center",
                        valign: "middle",
                        formatter: function (value, row, index) {
                            var result = [];
                            // result.push('<p class="updateFood glyphicon glyphicon-pencil"></p>/');
                            result.push('<a href="javascript:void(0);" class="updateFood">修改</a>/');
                            if(row["state"] == 0){
                                result.push('<a href="javascript:void(0);" class="upOfStockFood">上架</a>/');
                            }else{
                                result.push('<a href="javascript:void(0);" class="outOfStockFood">下架</a>/');
                            }

                            return result.join("");
                        },
                        events: {
                            'click .updateFood': function (e, value, row, index) {
                                This.ajaxTable.update(row);
                            },
                            'click .upOfStockFood': function (e, value, row, index) {
                                This.ajaxTable.stock([row["fid"]],"up");
                            },
                            'click .outOfStockFood': function (e, value, row, index) {
                                This.ajaxTable.stock([row["fid"]],"out");
                            }
                        }
                    }
                ]
            }).on("check.bs.table uncheck.bs.table 	check-all.bs.table uncheck-all.bs.table pre-body.bs.table",function () {
                var selections = This.tableBar.bootstrapTable("getSelections");
                var stock = getTool("stock");
                if(selections.length != 1){
                    getTool("update").attr("disabled",true);
                }else{
                    getTool("update").attr("disabled",false);
                }
            });
        },
        queryParams: function (params) {

        }
    };

    this.ajaxTable = {
        update:function (row) {
            if(!row || row == ""){
                return null;
            }
            var form = This.foodsForm;
            form.setType("update");
            form.$modal.hintModal().showDiv();
            form.param("picurl").next("img").attr("src",This.path+row["picurl"]);
            form.param("fid").val(row["fid"]);
            form.param("typeid").val(row["type"]["typeid"]);
            form.param("foodName").val(row["foodname"]);
            form.param("foodPrice").val(row["foodprice"]);
            form.param("foodVip").val(row["foodvip"]);
            form.param("feature").val(row["feature"]);
        },
        stock: function (ids, type) {
            if(ids.length == 0){
                return null;
            }
            var errorModal = This.errorBar.hintModal();
            errorModal.showHint("是否下架");
            var $button = This.errorBar.find(".btn-primary");
            $button.bind("click",function () {
                $button.attr("disabled",true);
                $.ajax({
                    type:"get",
                    url:"foods/stock",
                    data:{
                        ids:ids,
                        type:type
                    },
                    dataType:"json",
                    success:function (data) {
                        if(data["recode"] == "0"){
                            This.tableBar.bootstrapTable("refresh");
                            // errorModal.showError("",1200);
                            errorModal.hide();
                        }else{
                            errorModal.showError(data["error"],1200);
                            $button.attr("disabled",false);
                        }
                    }
                });
            });
        }
    };

    var addTool = function (html) {
        This.toolBar.append(html);
    };

    var addMyTool = function (html) {
        $(html).insertBefore(getMyTool("fClear"));
    };

    var getTool = function (name) {
        return This.toolBar.find("."+name);
    };
    
    var  getMyTool = function (name) {
        return This.myToolBar.find("."+name);
    }
}
